package com.ayi.dao.userdao;

import com.ayi.bean.User;
import com.ayi.utils.GetConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ayi.constants.BookShopConstants.ConstantMethods.*;

/**
 * @author Ayingzz
 * @create 2021/11/28 13:45
 */
public class QueryUser {

    /**
     * 通过id查找一个用户
     * @param id
     * @return
     */
    public User queryUserById(int id) {
        Connection conn = new GetConn().getConnection();
        String sql = "select * from Users where id = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            return getUser(rs);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过用户名查找一个用户
     * @param username
     * @return
     */
    public User queryUserByUserName(String username) {
        Connection conn = new GetConn().getConnection();
        String sql = "select * from Users where username = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            return getUser(rs);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查找不是管理员的用户
     * @return
     */
    public List<User> queryUserNotAdmin() {
        Connection conn = new GetConn().getConnection();
        String sql = "select * from Users where isAdmin = false";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            return getUsers(rs);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查找是管理员的用户
     * @return
     */
    public List<User> queryUserIsAdmin() {
        Connection conn = new GetConn().getConnection();
        String sql = "select * from Users where isAdmin = true";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            return getUsers(rs);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 初始化一个存储用户id的Map
     * @return
     */
    public Map<Integer, Integer> queryUserIdForInitEditStatus() {
        Map<Integer, Integer> map = new HashMap<>();
        Connection conn = new GetConn().getConnection();
        String sql = "select * from Users where isAdmin = true";
        return getInitMap(map, conn, sql);
    }

}
